package cn.lf.config;

import cn.lf.filter.CustomerJwtFilter;
import org.apache.shiro.mgt.DefaultSessionStorageEvaluator;
import org.apache.shiro.mgt.DefaultSubjectDAO;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.mgt.SessionsSecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.filter.InvalidRequestFilter;
import org.apache.shiro.web.filter.mgt.DefaultFilter;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author 啊胖
 */
@Configuration
public class ShiroConfig {

    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager){

        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();

        shiroFilterFactoryBean.setSecurityManager(securityManager);

        Map<String,Filter> filterMap = new HashMap<>();

        filterMap.put("customer", new CustomerJwtFilter());

        shiroFilterFactoryBean.setFilters(filterMap);

        Map<String,String> filterChainDefinitionMap = new LinkedHashMap<>();

        // 配置不会被拦截的链接 顺序判断
        filterChainDefinitionMap.put("/sys/login","anon");
        filterChainDefinitionMap.put("/sys/registerUser","anon");
        filterChainDefinitionMap.put("/sys/judgeSingle","anon");

        //swagger配置不拦截
        filterChainDefinitionMap.put("/webjars/**", "anon");
        filterChainDefinitionMap.put("/doc.html","anon");
        filterChainDefinitionMap.put("/swagger-resources/**","anon");
        filterChainDefinitionMap.put("/v2/api-docs","anon");

        //图片路径
        filterChainDefinitionMap.put("/imgfile/**","anon");

        filterChainDefinitionMap.put("/**","customer");

        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);

        InvalidRequestFilter invalidRequestFilter = new InvalidRequestFilter();

        invalidRequestFilter.setBlockNonAscii(false);

        shiroFilterFactoryBean.getFilters().put(DefaultFilter.invalidRequest.name(),invalidRequestFilter );

        return shiroFilterFactoryBean;

    }

    @Bean
    public SessionsSecurityManager securityManager(CustomerShiroRealm customerShiroRealm){

        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();

        securityManager.setRealm(customerShiroRealm);
//        DefaultSubjectDAO subjectDAO = new DefaultSubjectDAO();
//        DefaultSessionStorageEvaluator defaultSessionStorageEvaluator = new DefaultSessionStorageEvaluator();
//        defaultSessionStorageEvaluator.setSessionStorageEnabled(false);
//        subjectDAO.setSessionStorageEvaluator(defaultSessionStorageEvaluator);
//        securityManager.setSubjectDAO(subjectDAO);

        return securityManager;
    }

}
